import axios from 'axios'
import {BASE_URL} from "@/settings";
import router from "@/router";
import {ElMessage} from 'element-plus'

//  常规设置
const axiosInstance = axios.create({
    baseURL: BASE_URL,
    timeout: 1000 * 30,
    // withCredentials: true,
    headers: {
        'content-type': 'application/json'
    }
});

//  请求拦截器
axiosInstance.interceptors.request.use(
    (req) => {
        return req;
    },
    // (error) => Promise.reject(error));
    error => {
        ElMessage.error('请求被拒绝，请检查服务是否正常')
        return Promise.reject(error)
    })

// 响应拦截器
axiosInstance.interceptors.response.use(
    response => {
        // let data = response.data;
        // switch (data.code) {
        //     case -1:
        //         ElMessage.error('错误: ' + data.msg)
        //         break;
        //     case 0:
        //         // ElMessage.success(data.msg)
        //         break;
        //     case 40001:
        //         ElMessage.error("认证失败，请重新输入！")
        //         router.push("/login")
        //         break;
        //     case 40002:
        //         ElMessage.error("认证过期，请重新登录！")
        //         router.push("/login")
        //         break;
        //     default:
        //         ElMessage.error(data.detail)
        // }

        return response
    },
    error => {
        const code = error.response.status;
        switch (code) {
            case 401:
                ElMessage.warning('未认证，请登录！')
                router.push("/login");
                break
            case 403:
                ElMessage.warning('无权限操作')
                break
            case 404:
                ElMessage.error(error.response.data.title);
                break
            case 500:
                ElMessage.error('服务出错: ' + error.response.data.title);
                console.error(error.response.data.description);
                break
            default:
                ElMessage.error('连接错误')
        }
        return Promise.reject(error)
    }
);

export default {
    axiosInstance: axiosInstance
}